package org.glut.saltedfish.servlet;

import com.google.gson.Gson;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebInitParam;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.glut.saltedfish.domain.ApiResponse;
import org.glut.saltedfish.domain.Order;
import org.glut.saltedfish.service.OrderServiceImpl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 订单接口
 * </p>
 *
 * @author mjl
 * @since 2025/7/16
 */


@WebServlet(value={"/order/query", "/order/create", "/order/update", "/order/delete"}, initParams = {
        @WebInitParam(name = "appName", value = "订单管理系统"),
        @WebInitParam(name = "version", value = "1.0")
})
public class OrderServlet extends jakarta.servlet.http.HttpServlet {

    static Logger logger = Logger.getLogger(OrderServlet.class);

    /**
     * 初始化
     * @param config
     * @throws ServletException
     */
    @Override
    public void init(ServletConfig config) throws ServletException {
        String appName = config.getInitParameter("appName");
        String version = config.getInitParameter("version");
        logger.info("初始化订单Servlet: " + appName + " v" + version);
    }

    /**
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();

        String path = request.getServletPath();
        try {
            switch (path) {
                case "/order/query":
                    handleQuery(request, response);
                    break;
                case "/order/create":
                    handleCreate(request, response);
                    break;
                case "/order/update":
                    handleUpdate(request, response);
                    break;
                case "/order/delete":
                    handleDelete(request, response);
                    break;
                default:
                    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                    writer.write("{\"error\": \"无效的请求路径\"}");
            }
        } catch (Exception e) {
            logger.error("处理请求失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            writer.write("{\"error\": \"服务器内部错误\"}");
        }
    }

    // 辅助方法：设置查询参数
    private <T> void setQueryParam(HttpServletRequest request, String paramName, Class<T> type, java.util.function.Consumer<T> setter) {
        String paramValue = request.getParameter(paramName);
        if (paramValue != null && !paramValue.trim().isEmpty()) {
            try {
                if (type == Integer.class) {
                    setter.accept(type.cast(Integer.valueOf(paramValue)));
                } else if (type == String.class) {
                    setter.accept(type.cast(paramValue));
                }
            } catch (NumberFormatException e) {
                logger.warn("参数转换失败: " + paramName + "=" + paramValue, e);
            }
        }
    }

    private void handleQuery(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();

        // 创建订单查询条件对象
        Order queryCondition = new Order();

        // 设置查询条件
        setQueryParam(request, "buyerId", Integer.class, queryCondition::setBuyerId);//买家
        setQueryParam(request, "sellerId", Integer.class, queryCondition::setSellerId);//卖家
        setQueryParam(request, "productTitle", String.class, queryCondition::setProductTitle);//商品标题
        setQueryParam(request, "status", Integer.class, queryCondition::setStatus);//状态
        setQueryParam(request, "orderNo", String.class, queryCondition::setOrderNo);//订单编号

        // 设置分页参数
        int pageNum = 1;
        int pageSize = 5;
        try {
            pageNum = Integer.parseInt(request.getParameter("pageNum"));
            pageSize = Integer.parseInt(request.getParameter("pageSize"));
        } catch (NumberFormatException e) {
            logger.debug("使用默认分页参数", e);
        }

        // 确保分页参数合理
        pageNum = Math.max(1, pageNum);
        pageSize = Math.max(1, Math.min(pageSize, 20)); // 限制每页最大20条

        // 设置分页参数
        queryCondition.setOffset((pageNum - 1) * pageSize);
        queryCondition.setPageSize(pageSize);

        try {
            OrderServiceImpl orderService = new OrderServiceImpl();

            // 查询订单列表
            List<Order> orderList = orderService.selectByCondition(queryCondition);

            // 查询总数
            int total = orderService.countByCondition(queryCondition);

            // 构建返回结果
            Map<String, Object> data = new HashMap<>();
            data.put("list", orderList);
            data.put("pageNum", pageNum);
            data.put("pageSize", pageSize);
            data.put("total", total);
            data.put("totalPages", (int) Math.ceil((double) total / pageSize));

            writer.write(ApiResponse.success(data).toJson());
        } catch (Exception e) {
            logger.error("查询订单失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            writer.write("{\"error\": \"服务器内部错误，请稍后重试\"}");
        }
    }

    private void handleCreate(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        try {
            BufferedReader reader = request.getReader();
            Order order = new Gson().fromJson(reader, Order.class);

            if (order.getBuyerId() == null || order.getProductId() == null ||
                    order.getSellerId() == null || order.getAmount() == null) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                writer.write("{\"error\": \"缺少必要参数: buyerId, productId, sellerId 或 amount\"}");
                return;
            }

            if (order.getStatus() == null) {
                order.setStatus(0);
            }
            if (order.getOrderNo() == null) {
                order.setOrderNo(generateOrderNo());
            }

            OrderServiceImpl orderService = new OrderServiceImpl();
            boolean success = orderService.createOrder(order);

            if (success) {
                Map<String, String> data = new HashMap<>();
                data.put("orderNo", order.getOrderNo());
                writer.write(ApiResponse.success("订单创建成功", data).toJson());
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                writer.write(ApiResponse.error("订单创建失败").toJson());
            }
        } catch (Exception e) {
            logger.error("创建订单失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            writer.write("{\"error\": \"服务器内部错误\"}");
        }
    }

    private void handleUpdate(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        try {
            BufferedReader reader = request.getReader();
            Order order = new Gson().fromJson(reader, Order.class);

            if (order.getId() == null) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                writer.write("{\"error\": \"缺少必要参数: id\"}");
                return;
            }

            // 验证金额是否合法
            if (order.getAmount() != null && order.getAmount() <= 0) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                writer.write("{\"error\": \"金额必须大于0\"}");
                return;
            }

            OrderServiceImpl orderService = new OrderServiceImpl();
            boolean success = orderService.updateOrder(order);

            if (success) {
                writer.write(ApiResponse.success("订单更新成功", null).toJson());
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                writer.write(ApiResponse.error("订单更新失败").toJson());
            }
        } catch (Exception e) {
            logger.error("更新订单失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            writer.write("{\"error\": \"服务器内部错误\"}");
        }
    }
    private void handleDelete(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter writer = response.getWriter();
        try {
            Integer id = Integer.valueOf(request.getParameter("id"));
            if (id == null) {
                response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
                writer.write("{\"error\": \"缺少必要参数: id\"}");
                return;
            }

            OrderServiceImpl orderService = new OrderServiceImpl();
            boolean success = orderService.deleteOrder(id);

            if (success) {
                writer.write(ApiResponse.success("订单删除成功", null).toJson());
            } else {
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                writer.write(ApiResponse.error("订单删除失败").toJson());
            }
        } catch (Exception e) {
            logger.error("删除订单失败", e);
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            writer.write("{\"error\": \"服务器内部错误\"}");
        }
    }
    private String generateOrderNo() {
        return "ORD" + System.currentTimeMillis();
    }


    /**
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        doPost(request, response);
    }
}
